import {getMIMEBySuffix} from "@/utils/index";


let minioClient: any = {};

// const minioConfig: any = JSON.parse(decodeURIComponent(decodeURIComponent(store.state.minioData.minio)));
const minioConfig: any = (window as any).VUE_APP_URL[import.meta.env.MODE].minio;

// const loadMinio = asyn(window as any).VUE_APP_URL[import.meta.env.MODE]
//   await import("@/utils/minio");
//   minioClient = new (window as any).MinIO.Client({
//     endPoint: minioConfig.cloudUrl,
//     accessKey: minioConfig.cloudAccessKey,
//     secretKey: minioConfig.cloudSecretKey,
//   });
// };

const loadMinio = async () => {
  await import("@/utils/minio");
  minioClient = new (window as any).MinIO.Client({
    endPoint: minioConfig.endPoint,
    accessKey: minioConfig.accessKey,
    secretKey: minioConfig.secretKey,
    useSSL:minioConfig.useSSL,
    port:minioConfig.port,
  });
};
loadMinio();

export const upload = async (file: File, path: string) => {
  // minioConfig.toCloud = true
  // if(!minioConfig.toCloud) {
  //   return new Promise(async(resolve, reject) => {
  //     let formData = new FormData();
  //     formData.append("file", file); //file是blob数据
  //     let rs:any = await toolsApi.interfaceUpload(formData)
  //     if(rs.code === 200) {
  //       resolve({
  //         url: rs.payload.url,
  //         name: file.name,
  //       });
  //     }

  //   })
  // }

  return new Promise((resolve, reject) => {
    let fr = new FileReader(); //用FileReader 读取文件流
    fr.readAsArrayBuffer(file);
    fr.addEventListener("loadend", (e: any) => {
      //e.target.result 就是读取到的文件流 将其转为Buffer类型即可
      let type = file.name.split(".").pop();
      let filePath = path && !path.endsWith("/") ? `${path}/` : path;
      let fileName = `${Date.parse(new Date() as any)}${randomString(
        8
      )}.${type}`;
      minioClient.putObject(
        minioConfig.bucketName,
        `${filePath}${fileName}`,
        new Buffer(e.target.result),
        file.size,
        {
          "Content-Type": getMIMEBySuffix(type ?? ""),
          "Content-Length": file.size
        },
        function (err: any, objInfo: any) {
          if (err) {
            reject(err);
          }

          resolve({
            url: `${minioConfig.protocol}://${minioConfig.endPoint}${minioConfig.port?(':'+minioConfig.port):''}/${minioConfig.bucketName}/${filePath}${fileName}`,
            name: `${fileName}`,
          });
        }
      );
    });
  });
};

const randomString = (e: number) => {
  e = e || 32;
  let t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
    a = t.length,
    n = "";
  for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
  return n;
};
